export class cache {
    setCache(key, value, localOrSessionStorage = true) {
        try {
            const val = JSON.stringify(value);
            if (localOrSessionStorage) {
                window.localStorage.setItem(key, val);
            } else {
                window.sessionStorage.setItem(key, val);
            }
        } catch (error) {
            return false;
        }
        return true;
    }

    // 获取缓存
    getCache(key, localOrSessionStorage = true) {
        let res;
        if (localOrSessionStorage) {
            const val = window.localStorage.getItem(key);
            if (val) {
                res = JSON.parse(val);
            }
        }
        const val = window.sessionStorage.getItem(key);
        if (val) {
            res = JSON.parse(val);
        }
        return res;
    }

    removeCache(key, localOrSessionStorage = true) {
        if (localOrSessionStorage) window.localStorage.removeItem(key);
        else window.sessionStorage.removeItem(key);
    }

    clearCache(localOrSessionStorage = true) {
        if (localOrSessionStorage) window.localStorage.clear();
        else window.sessionStorage.clear();
    }
}

export default new cache();

